package tgc.edu.szxt.demo.service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import tgc.edu.szxt.demo.custom.BaseService;
import tgc.edu.szxt.demo.entity.Student;
import tgc.edu.szxt.demo.entity.SysRole;
import tgc.edu.szxt.demo.entity.TbClass;
import tgc.edu.szxt.demo.web.form.StudentForm;



@Service
public class XueshengService extends BaseService<Student, Integer>{
	@Value("${web.file-path}")
	private String path;
	
	@Autowired
	private SysRoleService sysRoleService;
	
	@Transactional
	public synchronized Boolean save(StudentForm form) {
		try {
			BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
			Integer id = form.getId();
			MultipartFile file = form.getFile();
			Student model=new Student();
			if(id!=null) {
				model=findById(id);
			}else {
				model.setPassword(encoder.encode("1111"));
				List<SysRole> role = new ArrayList<>();
				role.add(sysRoleService.findById(3));
				model.setRoles(role);
				model.setTbClass(new TbClass(form.getBjId()));
			}
			
			String originalFilename = file.getOriginalFilename();
			if(StringUtils.hasText(originalFilename)) {
				String uuid = model.getUuid();
				if(uuid!=null) {
					File f=new File(path,uuid);
					f.delete();
				}
				uuid=UUID.randomUUID().toString();
				model.setUuid(uuid);
				model.setFilename(originalFilename);
				File f=new File(path, uuid);
				file.transferTo(f);
			}
			BeanUtils.copyProperties(form, model,"id");
			model.setUsername(model.getStuNo());
			save(model);
			return true;
		} catch (Exception e) {
			return false;
		}
		
	}
	
	@Transactional
	public boolean delete(Integer id) {
		try {
			Student model = findById(id);
			String uuid = model.getUuid();
			File file=new File(path,uuid);
			if(file.exists()) {
				file.delete();
			}
			delete(model);
			return true;
		}catch (Exception e) {
			return false;
		}
	}

}
